<template>
  <a-modal
    title="授权"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleClose"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" :labelCol="labelCol" :wrapperCol="wrapperCol">
        <a-form-item label="用户名">
          <a-input v-model="username" disabled placeholder="用户名"/>
        </a-form-item>
        <a-form-item label="角色">
          <a-select mode="multiple"
                    style="width: 100%"
                    placeholder="无角色"
                    :allowClear="true"
                    v-model="roleCodes">
            <a-select-option v-for="selectData in roleSelectData"
                             :key="selectData.id">
              {{ selectData.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>
<script>

export default {
  name: 'ScopeModal',
  data () {
    return {
      visible: false,
      confirmLoading: true,
      form: this.$form.createForm(this),
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },

      userId: '',
      username: '',
      roleCodes: [],
      roleSelectData: []
    }
  },
  created () {
    // 获取角色列表
  },
  methods: {
    show (record) {
      console.log(record, 'record')
      this.visible = true
      this.confirmLoading = true

      this.userId = record.id
      this.username = record.username
      this.roleCodes = []
      // 获取角色列表
      this.getRoles()
      // 获取用户权限
      this.getUserRoles(this.userId)
    },
    // 获取角色列表
    getRoles () {
      this.$http('/rapid/role/getRoles', {}).then(res => {
        this.confirmLoading = false
        if (res.code === 200) {
          this.roleSelectData  = res.result
        }
      })
    },
    // 获取用户权限
    getUserRoles(userId) {
      this.$http('/rapid/user/findUserRole', {userId}).then(res => {
        this.confirmLoading = false
        if (res.code === 200) {
          this.roleCodes = res.result.map(item => {
            return item.id
          })
        }
      })
    },
    handleOk (e) {
      this.confirmLoading = true
      const data = {
        userId:this.userId, 
        roleIds:this.roleCodes
      }
      this.$http('/rapid/user/editUserRole', data).then(res => {
        this.confirmLoading = false
        if (res.code === 200) {
          this.$message.success('授权成功！')
          // 成功后重新查询用户角色
          this.getUserRoles(this.userId)
        }
      })
    },
    handleClose (e) {
      this.visible = false
      this.confirmLoading = false
    }
  }
}
</script>
